﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Net.Browser;
using System.ServiceModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Xml.Linq;
using ICSharpCode.SharpZipLib.Zip;
using SLBIARVerify.ClassLib;
//using SLBIARVerify.CRDWToolSetService;
using SLBIARVerify.CRDWToolSetWebService;
namespace SLBIARVerify
{
    public partial class MainPage : Page
    {
        //CRDWToolSetServiceClient service = new CRDWToolSetServiceClient();
        CRDWToolSetWebServiceClient service = new CRDWToolSetWebServiceClient();
        string BiarFileProperties = "0|0|0|0|0|0";

        string sourceXmlName = "businessobjects.xml";
        string targetXmlName = "targetBusinessObjects.xml";

        string targetBIARFileName = "";
        string sourceBIARFileName = "";

        public MainPage()
        {
            InitializeComponent();
            bool registerResult = WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
            bool httpsResult = WebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp);
           service.DocumentBiarToExcelCompleted+=new EventHandler<DocumentBiarToExcelCompletedEventArgs>(service_DocumentBiarToExcelCompleted);
        }

        private void button_IncreaseSpace_Click(object sender, RoutedEventArgs e)
        {
            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (isf.Quota < 50 * 1024 * 1024)
                {
                    isf.IncreaseQuotaTo(50 * 1024 * 1024);
                }
                else
                {
                    isf.IncreaseQuotaTo(isf.Quota + (50 * 1024 * 1024));
                }
            }
        }

        private void button_SelectBIAR_Click(object sender, RoutedEventArgs e)
        {
            try
            {

                OpenFileDialog dlg = new OpenFileDialog();
                dlg.Filter = "BIAR files|*.biar";
                if (dlg.ShowDialog() == true)
                {

                    if (!dlg.File.Name.ToLower().EndsWith("biar"))
                    {
                        MessageBox.Show("I can only accept BIAR file.", "Error", MessageBoxButton.OK);
                    }
                    else
                    {
                        busy.IsBusy = true;
                        btExportToExcel.IsEnabled = false;
                        btSelectBiar.IsEnabled = false;
                        btIncreaseSpace.IsEnabled = false;

                        FileInfo fi = dlg.File;
                        sourceBIARFileName = fi.Name;
                        BiarFileProperties = string.Format("{0}|{1}|{2}|{3}|{4}|{5}|", fi.Name, fi.Length, "MD5", 0, 0, 0);
                        using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            if (fi.Length > isf.AvailableFreeSpace)
                            {
                                MessageBox.Show("I need more free space to process your request. Position: 1" + Environment.NewLine + " Click Increase Space button to apply more free space.");
                            }
                            else
                            {

                                foreach (string item in isf.GetFileNames())
                                {
                                    isf.DeleteFile(item);
                                }

                                using (FileStream sourceStream = fi.OpenRead())
                                {
                                    using (ZipInputStream zipInputStream = new ZipInputStream(sourceStream))
                                    {
                                        ZipEntry oneZipEntry;
                                        while ((oneZipEntry = zipInputStream.GetNextEntry()) != null)
                                        {
                                            //using (IsolatedStorageFileStream stream = isf.CreateFile(sourceXmlName))
                                            string fileName = System.IO.Path.GetFileName(oneZipEntry.Name);
                                            using (IsolatedStorageFileStream stream = isf.CreateFile(fileName))
                                            {

                                                //    if (!string.IsNullOrEmpty(fileName) && fileName.ToLower().Equals("businessobjects.xml"))
                                                //{
                                                if (zipInputStream.Length > isf.AvailableFreeSpace)
                                                {
                                                    MessageBox.Show("I need more free space to process your request. . Position: 2" + Environment.NewLine + " Click Increase Space button to apply more free space.");
                                                    return;
                                                }
                                                else
                                                {
                                                    byte[] buffer = new byte[10240];
                                                    int count = 0;
                                                    do
                                                    {
                                                        count = zipInputStream.Read(buffer, 0, buffer.Length);
                                                        if (count > 0)
                                                        {
                                                            stream.Write(buffer, 0, count);
                                                        }
                                                    } while (count > 0);

                                                }
                                            }
                                        }
                                    }
                                }

                                if (isf.FileExists("businessobjects.xml"))
                                {
                                    using (IsolatedStorageFileStream xmlStream = isf.OpenFile("businessobjects.xml", FileMode.Open))
                                    {
                                        XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
                                        XNamespace io = "http://enterprise.businessobjects.com/infoobject";

                                        XElement root = XElement.Load(xmlStream);

                                        IEnumerable<NameCuidType> viewSet = root.Elements()
                                                                                    .Select(
                                                                                    c => new NameCuidType
                                                                                    {
                                                                                        Name = c.Element(io + "Name").Value,
                                                                                        Type = c.FirstAttribute.Value.Split(':')[1],
                                                                                        Cuid=c.Element(io+"Cuid").Value
                                                                                    });

                                        PagedCollectionView view = new PagedCollectionView(viewSet);
                                        view.SortDescriptions.Add(new SortDescription("Type", ListSortDirection.Ascending));
                                        view.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
                                        view.GroupDescriptions.Add(new PropertyGroupDescription("Type"));
                                        dg.ItemsSource = view;

                                        foreach (CollectionViewGroup oneGroup in view.Groups)
                                        {
                                            dg.CollapseRowGroup(oneGroup, true);
                                        }
                                        //summaryListBox.ItemsSource = set;

                                        btExportToExcel.IsEnabled = true;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            finally
            {
                btSelectBiar.IsEnabled = true;
                btIncreaseSpace.IsEnabled = true;

                busy.IsBusy = false;
            }
        }

        private void button_Export2Excel_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SaveFileDialog dlg = new SaveFileDialog();
                dlg.Filter = "Excel File(*.xlsx)|*.xlsx";
                dlg.DefaultExt = "xlsx";
                if (dlg.ShowDialog() == true)
                {

                    using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        string zipFilename = "";
                        if (isf.FileExists("businessobjects.xml"))
                        {

                            busy.IsBusy = true;
                            btExportToExcel.IsEnabled = false;
                            btSelectBiar.IsEnabled = false;
                            btIncreaseSpace.IsEnabled = false;

                            if (isf.FileExists("businessobjects.zip"))
                            {
                                isf.DeleteFile("businessobjects.zip");
                            }

                            using (FileStream sourceFile = isf.OpenFile("businessobjects.xml", FileMode.Open))
                            {

                                if (sourceBIARFileName.Length > 0)
                                {
                                    zipFilename = sourceBIARFileName.Replace("biar", "zip");
                                }
                                else
                                {
                                    zipFilename = "businessobjects.zip";
                                }
                                using (IsolatedStorageFileStream fileToUpload = isf.CreateFile(zipFilename))
                                {
                                    using (ZipOutputStream zipStream = new ZipOutputStream(fileToUpload))
                                    {
                                        ZipEntry entry = new ZipEntry("businessobjects.xml");
                                        zipStream.PutNextEntry(entry);
                                        byte[] buffer = new byte[10240];
                                        int count = 0;
                                        do
                                        {
                                            count = sourceFile.Read(buffer, 0, buffer.Length);
                                            if (count > 0)
                                            {
                                                zipStream.Write(buffer, 0, count);
                                            }
                                        } while (count > 0);
                                    }
                                }
                            }


                            if (isf.FileExists(zipFilename))
                            {
                                using (FileStream stream = isf.OpenFile(zipFilename, FileMode.Open))
                                {
                                    byte[] buffer = new byte[stream.Length];
                                    stream.Read(buffer, 0, buffer.Length);

                                    try
                                    {
                                        service.DocumentBiarToExcelAsync(zipFilename, buffer, BiarFileProperties, dlg);
                                    }
                                    catch (TimeoutException tout)
                                    {
                                        MessageBox.Show(tout.Message, "Time Out Error", MessageBoxButton.OK);
                                    }
                                    catch (CommunicationException cex)
                                    {
                                        MessageBox.Show(cex.Message, "Communication Error", MessageBoxButton.OK);
                                    }
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show("Give me a BIAR file please.");
                            btExportToExcel.IsEnabled = false;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK);
                btExportToExcel.IsEnabled = true;
                btSelectBiar.IsEnabled = true;
                btIncreaseSpace.IsEnabled = true;
                busy.IsBusy = false;
            }

        }

        void service_DocumentBiarToExcelCompleted(object sender, DocumentBiarToExcelCompletedEventArgs e)
        {
            try
            {
                byte[] buffer = e.Result;
                SaveFileDialog dlg = e.UserState as SaveFileDialog;
                
                using (Stream write = dlg.OpenFile())
                {
                    write.Write(buffer, 0, buffer.Length);
                }
                MessageBox.Show("Done. File Name is " + dlg.SafeFileName, "Done", MessageBoxButton.OK);
            }
            catch (TimeoutException tout)
            {
                MessageBox.Show(tout.Message, "Time Out Error", MessageBoxButton.OK);
            }
            catch (CommunicationException cex)
            {
                MessageBox.Show(cex.Message, "Communication Error", MessageBoxButton.OK);
            }
            catch (Exception ex)
            {
                if (ex.InnerException is TimeoutException)
                {
                    MessageBox.Show("Time Out.", "Time Out Error", MessageBoxButton.OK);
                }
                else if (ex.InnerException is CommunicationException)
                {
                    MessageBox.Show("Communication Error", "Communication Error", MessageBoxButton.OK);
                }
                else
                {
                    MessageBox.Show(ex.Message
                        + " Position: DocumentBiarToExcelCompleted"
                        + Environment.NewLine, "Error"
                        + ex.InnerException.Message
                        , MessageBoxButton.OK);

                }
            }
            finally
            {
                btExportToExcel.IsEnabled = true;
                btSelectBiar.IsEnabled = true;
                btIncreaseSpace.IsEnabled = true;
                busy.IsBusy = false;
            }
        }


        private void btComparison_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "BIAR files|*.biar";
            if (dlg.ShowDialog() == true)
            {
                if (!dlg.File.Name.ToLower().EndsWith("biar"))
                {
                    MessageBox.Show("I can only accept BIAR file.", "Error", MessageBoxButton.OK);
                }
                else
                {
                    FileInfo fi = dlg.File;
                    targetBIARFileName = fi.Name;
                    using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (fi.Length > isf.AvailableFreeSpace)
                        {
                            MessageBox.Show("I need more free space to process your request." + Environment.NewLine + " Click Increase Space button to apply more free space.");
                        }
                        else
                        {
                            using (FileStream sourceStream = fi.OpenRead())
                            {
                                using (ZipInputStream zipInputStream = new ZipInputStream(sourceStream))
                                {
                                    ZipEntry oneZipEntry;
                                    while ((oneZipEntry = zipInputStream.GetNextEntry()) != null)
                                    {
                                        using (IsolatedStorageFileStream targetXmlStream = isf.CreateFile(targetXmlName))
                                        {
                                            string fileName = System.IO.Path.GetFileName(oneZipEntry.Name);
                                            if (!string.IsNullOrEmpty(fileName) && fileName.ToLower().Equals("businessobjects.xml"))
                                            {
                                                if (zipInputStream.Length > isf.AvailableFreeSpace)
                                                {
                                                    MessageBox.Show("I need more free space to process your request." + Environment.NewLine + " Click Increase Space button to apply more free space.");
                                                }
                                                else
                                                {
                                                    byte[] buffer = new byte[10240];
                                                    int count = 0;
                                                    do
                                                    {
                                                        count = zipInputStream.Read(buffer, 0, buffer.Length);
                                                        if (count > 0)
                                                        {
                                                            targetXmlStream.Write(buffer, 0, count);
                                                        }
                                                    } while (count > 0);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        string uriStr = string.Format("/BIARComparison.xaml?SourceXmlFileName={0}&TargetXmlFileName={1}&SourceBIARFileName={2}&TargetBIARFileName={3}", sourceXmlName, targetXmlName, sourceBIARFileName, targetBIARFileName);
                        this.NavigationService.Navigate(new Uri(uriStr, UriKind.Relative));
                    }
                }
            }

        }

        private void btBIARReduction_Click(object sender, RoutedEventArgs e)
        {
            string uriStr = string.Format("/Reduction?BIARFileName={0}", sourceBIARFileName);
            this.NavigationService.Navigate(new Uri(uriStr, UriKind.Relative));
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            displayVersionNumber.Text = "Version Number: 0.0.20120401.1";

        }




    }

}
